package com.hdu.hot100.backTrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class lc39 {
    class Solution {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            f(candidates, 0, target, 0);
            return ans;
        }

        void f(int[] candidates, int curSum, int targetSum, int index)
        {
            if (curSum == targetSum)
            {
                ans.add(new ArrayList<>(path));
                return;
            }
            for (int i = index; i < candidates.length; i++)
            {
                if (curSum + candidates[i] > targetSum)
                {
                    return;
                }
                path.add(candidates[i]);
                f(candidates, curSum + candidates[i], targetSum, i);
                path.remove(path.size() - 1);
            }
        }
    }
}
